package com.spark.demonetty.netty_http;

import com.spark.demonetty.netty_demo.server.AbstractServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author fuqiang
 * @Description http文件服务器
 * @Date 2020/10/22
 */
public class HttpFileServer extends AbstractServer {

    private static final String DEFAULT_URL = "/demo/src/main/java/com/spark/demo";

    @Override
    public ServerBootstrap getDefaultBootstrap() {
        return null;
    }

    @Override
    public ServerBootstrap getDefaultBootstrap(String url) {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("http-decoder",new HttpRequestDecoder());
                        ch.pipeline().addLast("http-aggregator",new  HttpObjectAggregator(65536));
                        ch.pipeline().addLast("http-encoder",new HttpResponseEncoder());
                        ch.pipeline().addLast("http-chunked",new ChunkedWriteHandler());
                        ch.pipeline().addLast("fileServerHandler",new HttpFileServerHandler(url));
                    }
                });
        return b;
    }

    public static void main(String[] args) {
        int port = 10010;
        if(args != null && args.length > 0){
            port = Integer.valueOf(args[0]);
        }
        String url = DEFAULT_URL;
        if(args.length > 1){
            url = args[1];
        }
        new HttpFileServer().run(port,url,"192.168.7.148");
    }

}
